package com.terry.test1.org;

import cn.hutool.core.util.PhoneUtil;

import javax.xml.bind.ValidationException;
import java.util.Arrays;

public class RegistrationServiceImpl implements RegistrationService{

    private SaleRepRepository saleRepRepository;
    private UserRepository userRepository;

    @Override
    public User register(String name, String phone, String address) throws ValidationException {
        //1.校验name 可通过validation  @Empty实现
        if(name == null || name.length() == 0){
            throw new ValidationException("name");
        }
        if(phone == null || PhoneUtil.isPhone(phone)){
            throw new ValidationException("phone");
        }

        //2.取电话里的区号
        String areaCode = null;
        String[] areas = new String[]{"0571", "021", "010"};
        for (int i = 0; i < phone.length(); i++) {
            String prefix = phone.substring(0, i);
            if (Arrays.asList(areas).contains(prefix)) {
                areaCode = prefix;
                break;
            }
        }
        //根据区号查找合伙人
        SaleRep saleRep = saleRepRepository.findRep(areaCode);

        //创建用户,落库
        User user = new User();
        user.setAdress(address);
        user.setName(name);
        user.setPhone(phone);
        if(saleRep != null){
            user.setRepId(saleRep.getRepId());
        }
        return userRepository.save(user);
    }
}
